package br.embedded.socialapp.business;

import org.opensocial.Client;
import org.opensocial.Request;
import org.opensocial.RequestException;
import org.opensocial.Response;
//import org.opensocial.services.ActivitiesService;
import org.opensocial.services.AppDataService;
import org.opensocial.services.PeopleService;
//import org.opensocial.models.Activity;
import org.opensocial.models.Person;
import org.opensocial.models.AppData;

import com.twmacinta.util.MD5;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.Hashtable;
import java.util.List;

import br.embedded.socialapp.domain.User;
import br.embedded.socialapp.exceptions.UserException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;



public class DisplayExtendedProfileData {

  public static void main(String[] args) {
    
    Client c = OpenSocialClientFactory.getInstance("ORKUT_SANDBOX");
    
    /******
     * Friend 1: 
     * OpenSocialID: 01206547157695522917
     * OrkutID: 6006240336896373004
     * 
     * Friend 2: 
     * OpenSocialID = 06185051281244906819
     * OrkutID = 1654890334340069871
     */

    try {
    	Request request = PeopleService.getFriends("05504131713099562528");
 //   	request.setFieldsParameter(new String[] { "@all" });
    	Response response =  c.send(request);
    	List<Person> list = response.getEntries();
    	
    	for (Person person : list) {
    		System.out.println(person.getId());
			System.out.println(person.getDisplayName());
		}
	} catch (RequestException e1) {
		e1.printStackTrace();
	} catch (IOException e1) {
		e1.printStackTrace();
	}
	
	List<User>  list =  FriendManager.getInstance().fetchFriends("05504131713099562528", "ORKUT_SANDBOX", true);
	
	for (User user : list) {
		System.out.println(user.getPname().getGivenName());
		System.out.println(user.getPname().getFamilyName());

		/*for (String movie : user.getMovies()) {
			System.out.println(movie.trim());
		}*/
	}
	
/*	Activity activity = new Activity();
	activity.setTitle("teste");
	activity.setBody("funciona");
	Request request = ActivitiesService.createActivity(activity);
	try {
		c.send(request);
	} catch (RequestException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
*/
	
	
	try {
/*		UserManager.getInstance().createUser("johndoe", "John", "Doe", getMD5("123456"));
		UserManager.getInstance().createUser("beltranosilva", "Beltano", "Silva", getMD5("123456"));
		UserManager.getInstance().createUser("sicranasantos", "Sicrana", "Santos", getMD5("123456"));
		UserManager.getInstance().createUser("fulanosousa", "Fulano", "Sousa", getMD5("123456"));
*/		
		Request request = AppDataService.getAppData("16402456860419996289");
		Response response = c.send(request);
		AppData userData = response.getEntry();
		System.out.println(userData.getDataForUser("16402456860419996289", "token"));
		
		request = AppDataService.getFriendAppData("05504131713099562528");
		response = c.send(request);
		List<AppData> friendsData = response.getEntries();
		AppData appData = friendsData.get(0);
		
		Hashtable<String, String> hash = new Hashtable<String, String>();
		
		for (User friend : list) {
			UserManager.getInstance().doLogin("johndoe", getMD5("123456"));
			String[] data = getValues(appData.getDataForUser(friend.getId(), "token"));
			UserManager.getInstance().updateSocialNetworkId(data[0], data[2], data[1]);
			hash.put(data[0], data[1]);
		}
		
		
	} catch (RequestException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} catch (UserException e) {
		e.printStackTrace();
	}
	
	
	System.out.println(getMD5("123"));
	System.out.println(stringHexa(gerarHash("123", "MD5")));
	System.out.println(Criptografar("123"));
  }
  
  private static String getMD5(String pwd)
  { 
	  MessageDigest md = null;
	  BigInteger hash;
	  String result = "";
	  try
	  {  
		  md = MessageDigest.getInstance("MD5");
		  hash = new BigInteger(1, md.digest(pwd.getBytes("UTF-8")));
		  result = hash.toString(16);
	  }
	  catch (NoSuchAlgorithmException e)
	  {  
		  e.printStackTrace();
	  } catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}  
	  return result;
  }
  
  public static byte[] gerarHash(String frase, String algoritmo)
  {
	  try
	  {
		  MessageDigest md = MessageDigest.getInstance(algoritmo);
		  md.update(frase.getBytes());
		  return md.digest();
	  }
	  catch (NoSuchAlgorithmException e) {
		  return null;
	  }
  }

  private static String stringHexa(byte[] bytes)
  {
	  StringBuilder s = new StringBuilder();
	  for (int i = 0; i < bytes.length; i++) {
		  int parteAlta = ((bytes[i] >> 4) & 0xf) << 4;
		  int parteBaixa = bytes[i] & 0xf;
		  if (parteAlta == 0) s.append('0');
		  s.append(Integer.toHexString(parteAlta | parteBaixa));
	  }
	  return s.toString();
  }
  
  private static String Criptografar(String pwd)
  {
	  //converter o texto em bytes  
	  byte plain[] = pwd.getBytes();  
	  // criar um objeto MD5Hash passando a sequencia de bytes resultante do texto digitado  
	  MD5 md5 = new MD5(plain);  
	  // pegando o resultado hash gerado  
	  byte[] result = md5.doFinal();  
	  // convertendo o conjunto de bytes em hexadecimal e aplicando ao objeto texto do display  
	  return MD5.toHex(result); 
  }
  
  private static String[] getValues(String token)
  {
	  token = token.replace("\"", "");
	  token = token.replace("{", "").trim();
	  token = token.replace("}", "").trim();
	  token = token.replace(",", ":").trim();
	  
	  String[] tokens = token.split(":");
	  String[] result = { tokens[2], tokens[4], tokens[6].replace(".com", "").trim() };
	  
	  return result;
  }

}